package com.blobfish.fiction.common.download;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.blobfish.fiction.book.service.impl.BookServiceImpl;
import com.blobfish.fiction.common.base.knowledge.DataDictKnowledge;
import com.blobfish.fiction.common.model.Book;
import com.blobfish.fiction.common.pageprocessor.WujixiaoshuoPageProcessor;
import com.blobfish.fiction.common.pipeline.WujixiaoshuoPipeline;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.redis.Redis;
import us.codecraft.webmagic.Spider;

/**
 * 下载线程
 */
public class DownloadThread extends Thread {
    private static final Log log = Log.getLog(DownloadThread.class);
    private BookServiceImpl bookService;
    private final DownloadQueue downloadQueue;

    /**
     * 构造方法
     * @param name 下载线程名称
     * @param downloadQueue 下载任务队列
     */
    public DownloadThread(String name, DownloadQueue downloadQueue, BookServiceImpl bookService) {
        super(name);
        this.downloadQueue = downloadQueue;
        this.bookService = bookService;
    }

    @Override
    public void run() {
        try {
            while (true) {
                String bookNo = downloadQueue.take();
                log.info(StrUtil.format("【{}】:开始下载【{}】------", this.getName(), bookNo));
                long startTime = System.currentTimeMillis();
                // 开始下载开说
                Spider.create(new WujixiaoshuoPageProcessor())
                        .addPipeline(new WujixiaoshuoPipeline())
                        .addUrl(StrUtil.format("https://m.wujixiaoshuo.com/{}/all.html", bookNo)).thread(5).run();
                long endTime = System.currentTimeMillis();
                Book book = bookService.getByBookNo(bookNo);
                book.setState(DataDictKnowledge.BookStateEnum.DOWNLOADED.getDataCode());
                book.update();
                // 删除对应缓存
                Redis.use("master").srem(PropKit.get("cacheName.DOWNLOADED_BOOK_NO"), bookNo);
                log.info(StrUtil.format("【{}】:【{}】下载完成,耗时{}ms", this.getName(), bookNo, endTime - startTime));
                ThreadUtil.safeSleep(500);
            }
        } catch (InterruptedException e) {
            log.error(e.getMessage());
        }
    }
}
